package service

import (
	"api/app/logs/documents"
	"gitee.com/dreamwood/ez"
	"net/http"
	"strings"
	"time"
)

func LogToMongodb(response *http.Response, body []byte) {
	if !checkIsApi(response) {
		return
	}

	req := response.Request
	//requestBody, _ := io.ReadAll(req.Body)
	ez.JsonLog(req.Header.Get("ChanKey"))
	log := new(documents.EZRequestLog)

	log.CreateAt = time.Now()
	log.ChainKey = req.Header.Get("ChanKey")
	log.HOST = req.Host
	log.URL = req.URL.String()
	log.Method = req.Method
	log.Referer = req.Referer()
	log.RemoteAddr = req.RemoteAddr
	log.UserAgent = req.Header.Get("User-Agent")
	log.XAUTHTOKEN = req.Header.Get("X-AUTH-TOKEN")
	log.AccessToken = req.Header.Get("a-auth-token")
	//body, l := io.ReadAll(response.Body)
	//ez.Debug(l)
	log.Response = string(body)

	//文件类型
	//response.Header.Get("Content-Type")
	log.Flag = response.Header.Get("Content-Type")

	log.Save()
}

func checkIsApi(response *http.Response) bool {
	contentType := response.Header.Get("Content-Type")

	if strings.Contains(contentType, "application/json") {
		return true
	}

	url := response.Request.URL.String()
	if strings.Contains(url, "/api/") {
		return true
	}
	if strings.Contains(url, "/_heart_beat") {
		return false
	}
	if strings.Contains(url, "/_heart_beat") {
		return false
	}
	return false

}
